//
//  PublishNeedViewController.m
//  ForestPack
//
//  Created by 郑洲 on 2018/7/17.
//  Copyright © 2018年 郑洲. All rights reserved.
//

#import "PublishNeedViewController.h"
#import "CompleteConmmandInfoViewController.h"
#import "FPPublicDemandCell.h"
#import "NeedSelectTableViewCell.h"
#import "FPPublicDemandCell.h"
#import "TypeSelectView.h"
#import "FPCustomButton.h"

typedef NS_ENUM(NSInteger, NeedType) {
    NeedType_Bid,
    NeedType_Pitch,
    NeedType_Piecework
};

@interface PublishNeedViewController ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, UITextViewDelegate,CTAssetsPickerControllerDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate> {
    UIButton *bargainBtn;
    UITextView *contentText;
    UIButton *shadowBtn;
}

@property (nonatomic, strong) BaseTableView *tableView;
@property (nonatomic, strong) TypeSelectView    *boxTypeView;
//@property (nonatomic, strong) BaseTableView * tableView;
//@property (nonatomic,strong)  UITextField   * textTypeField;
@property (nonatomic,strong)  NSString      * phoneNum;

@property (nonatomic, assign) NeedType       needType;
@property (nonatomic, assign) NSInteger      needNum;
@property (nonatomic, assign) NSInteger      selectType;
@property (nonatomic, strong) NSMutableArray *imageArray;

@property (nonatomic, strong) UIDatePicker *dataPicker;
@property (nonatomic, strong) UIView *pickViewToobar;//pickview的完成工具条
@property (nonatomic, copy)   NSString *selectTime;

@property (nonatomic,strong)  UITextField   * typeField;
@property (nonatomic,strong)  UITextField   * valueField;
@property (nonatomic,strong)  UITextField   * timeField;
@property (nonatomic,strong)  UITextField   * numField;

@end

@implementation PublishNeedViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"发布竞标需求";
    self.view.backgroundColor = TABLEVIEW_BACKGROUNDCOLOR;
    
    _needType = NeedType_Bid;
    _needNum = 2;
    _selectType = 0;
    _phoneNum = kNSUDefaultReadKey(@"phone");
    self.imageArray = [NSMutableArray array];
    
    [self setTableViewUI];
    
}

-(void)setTableViewUI
{
    self.tableView = [[BaseTableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - NAVIGATION_BAR_HEIGHT) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = ScreenX375(108);
    [self.view addSubview:self.tableView];
}

- (void)commit {
    UITextField *typeField = [self.view viewWithTag:600];
    if (typeField.text.length == 0) {
        [HttpManager showNoteMsg:@"请选择类目"];
        return;
    }
    UITextField *feeField = [self.view viewWithTag:601];
    if (typeField.text.length == 0) {
        [HttpManager showNoteMsg:@"请填写预算"];
        return;
    }
    UITextField *timeField = [self.view viewWithTag:602];
    if (typeField.text.length == 0) {
        [HttpManager showNoteMsg:@"请填写截止日期"];
        return;
    }
    NSString *rate = @"";
    if (_needType == NeedType_Pitch) {
        for (int i = 0; i < _needNum; i++) {
            UITextField *textField = [self.view viewWithTag:604 + i];
            if (textField.text.length == 0) {
                [HttpManager showNoteMsg:@"请填写完奖金比例"];
                return;
            }else {
                rate = [NSString stringWithFormat:@"%@,%@",rate,textField.text];
            }
        }
        if (rate.length > 0) {
            rate = [rate substringFromIndex:1];
        }
    }
    NSString *type = @"";
    if (_needType == NeedType_Bid) {
        type = @"11";
    }else if (_needType == NeedType_Pitch) {
        type = @"12";
    }else if (_needType == NeedType_Piecework) {
        type = @"13";
    }
    
    NSMutableDictionary *parameter = [NSMutableDictionary dictionaryWithDictionary:@{@"token":[FPLoginAndRegisterTools getToken],@"total_fee":feeField.text,@"type":type,@"mobile":@"15757166497",@"is_bargaining":[NSNumber numberWithBool:bargainBtn.isSelected],@"demand":contentText.text,@"deadline":timeField.text,@"category":typeField.text}];
    if (_needType != NeedType_Bid) {
        UITextField *draftField = [self.view viewWithTag:603];
        if (typeField.text.length == 0) {
            [HttpManager showNoteMsg:@"请填写取稿数量"];
        }
        [parameter setObject:draftField.text forKey:@"draft"];
    }
    if (self.imageArray.count > 0) {
        [HttpManager uploadImageArr:self.imageArray success:^(id successResponse) {
            NSMutableArray *imageStrArray = successResponse;
            NSString * detail_pic = @""; ///, [0], [1]
            for (NSString * urlStr in imageStrArray) {
                if ([detail_pic isEqualToString:@""]) {
                    detail_pic = urlStr;
                }else{
                    detail_pic = [NSString stringWithFormat:@"%@,%@",detail_pic, urlStr]; /// [0], [1]
                }
            }
            [parameter setObject:detail_pic forKey:@"pic"];
            [HttpManager postHttpRequestByPost:[NSString stringWithFormat:@"%@app/create_draft_order",REQUESTHEADER] andParameter:parameter success:^(id successResponse) {
                NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"status"]];
                if ([status isEqualToString:@"1"]) {
                    [HttpManager hideWait];
                    [HttpManager showNoteMsg:@"提交成功"];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [self.navigationController popViewControllerAnimated:YES];
                    });
                }
            } andFailure:^(id failureResponse) {
                [HttpManager showFail];
            }];
        }];
    }else {
        [HttpManager postHttpRequestByPost:[NSString stringWithFormat:@"%@app/create_draft_order",REQUESTHEADER] andParameter:parameter success:^(id successResponse) {
            NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"status"]];
            if ([status isEqualToString:@"1"]) {
                [HttpManager showNoteMsg:@"提交成功"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.navigationController popViewControllerAnimated:YES];
                });
            }
        } andFailure:^(id failureResponse) {
            [HttpManager showFail];
        }];
    }
}

- (void)isBargain:(UIButton *)button {
    button.selected = !button.isSelected;
}

- (void)selectClass {
    [self.view endEditing:YES];
    self.boxTypeView = [[TypeSelectView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT)];
    NSArray *noteArr = @[@"彩印设计",@"水印设计",@"数码设计",@"结构设计"];
    [self.boxTypeView modelArrayForView:noteArr andSelect:_selectType];
    __weak __typeof(self) weakSelf = self;
    self.boxTypeView.hiddenClick = ^{
        [weakSelf hidden];
    };
    self.boxTypeView.doneClick = ^(NSInteger selectIndex) {
        weakSelf.selectType = selectIndex;
        UITextField *typeLabel = [weakSelf.view viewWithTag:600];
        typeLabel.text = noteArr[weakSelf.selectType];
        [weakSelf hidden];
    };
    [kKeyWindow addSubview:self.boxTypeView];
    [self.view endEditing:YES];
    [UIView animateWithDuration:0.3 animations:^{
        self.boxTypeView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    } completion:^(BOOL finished) {
        self.boxTypeView.shadowBtn.alpha = 1;
    }];
}

- (void)selectedTime {
    [self.view endEditing:YES];
    if (!shadowBtn) {
        shadowBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        shadowBtn.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
        [shadowBtn addTarget:self action:@selector(hiddenPickView) forControlEvents:UIControlEventTouchUpInside];
        shadowBtn.hidden = YES;
        [self.view addSubview:shadowBtn];
    }
    if (!_pickViewToobar) {
        [self setPickerToobar];
    }
    if (!_dataPicker) {
        _dataPicker = [[UIDatePicker alloc] init];
        _dataPicker.frame = CGRectMake(0,CGRectGetMaxY(_pickViewToobar.frame), SCREEN_WIDTH, SCREEN_WIDTH / 375 * 260 - 44); // 设置显示的位置和大小
        _dataPicker.date = [NSDate date]; // 设置初始时间
        _dataPicker.backgroundColor = [UIColor whiteColor];
        _dataPicker.timeZone = [NSTimeZone timeZoneWithName:@"GTM+8"]; // 设置时区，中国在东八区
        _dataPicker.datePickerMode = UIDatePickerModeDate; // 设置样式
        [_dataPicker addTarget:self action:@selector(datePickerValueChanged:) forControlEvents:UIControlEventValueChanged]; // 添加监听器
        [self.view addSubview:_dataPicker];
    }
    //判断pickerView的位置
    if (_dataPicker.frame.origin.y == SCREEN_HEIGHT+44) {
        
        [UIView animateWithDuration:0.3 animations:^{
            self->shadowBtn.hidden = NO;
            self.dataPicker.frame = CGRectMake(0, SCREEN_HEIGHT - (SCREEN_HEIGHT + NAVIGATION_BAR_HEIGHT) / 2.5 + 44, SCREEN_WIDTH, (SCREEN_HEIGHT + NAVIGATION_BAR_HEIGHT) / 2.5 - 44);
            self.pickViewToobar.frame = CGRectMake(0,CGRectGetMinY(self.dataPicker.frame)-44, SCREEN_WIDTH, 44);
            
        }];
        
    }else{
        
        [UIView animateWithDuration:0.3 animations:^{
            self->shadowBtn.hidden = YES;
            self.pickViewToobar.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 44);
            self.dataPicker.frame = CGRectMake(0, CGRectGetMaxY(self.pickViewToobar.frame), SCREEN_WIDTH, (SCREEN_HEIGHT + NAVIGATION_BAR_HEIGHT) / 2.5 - 44);
        }];
    }
}

//点击pickView的工具条操作按钮
- (void)pickViewOperateClick:(UIButton *)sender{
    
    if (sender.tag == 1) {
        //完成
        [self hiddenPickView];
        UITextField *textField = [self.view viewWithTag:602];
        textField.text = _selectTime;
    }else{
        //取消
        [self hiddenPickView];
    }
}

- (void)datePickerValueChanged:(UIDatePicker *) sender {
    
    NSDate *select = [sender date]; // 获取被选中的时间
    NSDateFormatter *selectDateFormatter = [[NSDateFormatter alloc] init];
    selectDateFormatter.dateFormat = @"yyyy-MM-dd"; // 设置时间和日期的格式
    _selectTime = [selectDateFormatter stringFromDate:select]; // 把date类型转为设置好格式的string类型
}

- (void)setPickerToobar {
    //工具条
    _pickViewToobar = [[UIView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 44)];
    _pickViewToobar.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_pickViewToobar];
    
    for (int i = 0; i < 2; i++) {
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, i * 43.5, SCREEN_WIDTH, 0.5)];
        line.backgroundColor = LineColor;
        [_pickViewToobar addSubview:line];
    }
    
    UIButton *cancleBtn = [[UIButton alloc]initWithFrame:CGRectMake(15, 0, 40, _pickViewToobar.frame.size.height)];
    [cancleBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancleBtn setTitleColor:ThemeColor forState:UIControlStateNormal];
    [cancleBtn addTarget:self action:@selector(pickViewOperateClick:) forControlEvents:UIControlEventTouchUpInside];
    [_pickViewToobar addSubview:cancleBtn];
    
    UIButton *achiveBtn = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH - 50, 0, 40, _pickViewToobar.frame.size.height)];
    [achiveBtn setTitle:@"完成" forState:UIControlStateNormal];
    achiveBtn.tag = 1;
    [achiveBtn setTitleColor:ThemeColor forState:UIControlStateNormal];
    [achiveBtn addTarget:self action:@selector(pickViewOperateClick:) forControlEvents:UIControlEventTouchUpInside];
    [_pickViewToobar addSubview:achiveBtn];
}


- (void)hiddenPickView{
    
    [UIView animateWithDuration:0.3 animations:^{
        self->shadowBtn.hidden = YES;
        self.pickViewToobar.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 44);
        self.dataPicker.frame = CGRectMake(0, CGRectGetMaxY(self.pickViewToobar.frame), SCREEN_WIDTH, (SCREEN_HEIGHT + NAVIGATION_BAR_HEIGHT) / 2.5);
    }];
}

- (void)hidden {
    self.boxTypeView.shadowBtn.alpha = 0;
    [UIView animateWithDuration:0.3 animations:^{
        self.boxTypeView.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT);
    }];
}

- (void)changePhone {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"修改联系方式" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        [textField addTarget:self action:@selector(textFieldChange:) forControlEvents:UIControlEventEditingChanged];
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (self.phoneNum.length != 11) {
            [HttpManager showNoteMsg:@"请输入正确的手机号码"];
            return ;
        }
        [self.tableView reloadSections:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(3, 1)] withRowAnimation:UITableViewRowAnimationNone];
    }];
    
    [alertController addAction:cancel];
    [alertController addAction:sure];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)textFieldChange:(UITextField *)textField {
    self.phoneNum = textField.text;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 5;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 3;
    }else if (section == 1) {
        if (_needType == NeedType_Bid) {
            return 3;
        }else if (_needType == NeedType_Pitch) {
            return 4 + _needNum;
        }
        return 4;
    }
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        NSArray *titleArr = @[@"竞标",@"比稿",@"计件"];
        NeedSelectTableViewCell *cell = [NeedSelectTableViewCell cellWithTableView:tableView andIndexPath:indexPath];
        if (indexPath.row == _needType) {
            [cell setStatus:YES andTitle:titleArr[indexPath.row]];
        }else {
            [cell setStatus:NO andTitle:titleArr[indexPath.row]];
        }
        return cell;
    }else if (indexPath.section == 1) {
        NSArray *noteArr = @[@"您想要做：",@"您的预算：",@"截止时间：",@"取稿数量："];
        NSArray *placeArr = @[@"请选择类目",@"请选择您的预算",@"请输入您的截止时间",@"请输入您的取稿数量",@"请输入奖金比例"];
        static NSString *cellId = @"detailCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            if (indexPath.row == 0) {
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            }else {
                cell.accessoryType = UITableViewCellAccessoryNone;
            }
            
            UILabel *noteLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(13), 0, ScreenX375(77), ScreenX375(47))];
            if (indexPath.row <= 3) {
                noteLabel.text = noteArr[indexPath.row];
            }else {
                noteLabel.text = [NSString stringWithFormat:@"排名%ld：",indexPath.row - 3];
            }
            noteLabel.tag = 500 + indexPath.row;
            noteLabel.textColor = REXADECIMALCOLOR(@"#333333");
            noteLabel.font = Kfont(14);
            [cell addSubview:noteLabel];
            
            UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(ScreenX375(90), 0, SCREEN_WIDTH - ScreenX375(110), ScreenX375(47))];
            if (indexPath.row <= 3) {
                textField.placeholder = placeArr[indexPath.row];
            }else {
                textField.placeholder = placeArr[4];
            }
            textField.font = Kfont(14);
            textField.tag = 600 + indexPath.row;
            textField.delegate = self;
            if (indexPath.row == 3) {
                textField.keyboardType = UIKeyboardTypeNumberPad;
            }
            if (indexPath.row == 0 && !_typeField) {
                _typeField = textField;
            }else if (indexPath.row == 1 && !_valueField) {
                _valueField = textField;
            }else if (indexPath.row == 2 && !_timeField) {
                _timeField = textField;
            }else if (indexPath.row == 3 && !_numField) {
                _numField = textField;
            }
            if (indexPath.row == 0 &&_typeField) {
                [cell addSubview:_typeField];
            }else if (indexPath.row == 1 && _valueField) {
                [cell addSubview:_valueField];
            }else if (indexPath.row == 2 && _timeField) {
                [cell addSubview:_timeField];
            }else if (indexPath.row == 3 && _numField) {
                [cell addSubview:_numField];
            }else {
                [cell addSubview:textField];
            }
            
            if (indexPath.row == 0) {
                UIButton *selectType = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ScreenX375(47))];
                selectType.backgroundColor = [UIColor clearColor];
                [selectType addTarget:self action:@selector(selectClass) forControlEvents:UIControlEventTouchUpInside];
                [cell addSubview:selectType];
            }else if (indexPath.row == 2) {
                UIButton *selectTime = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ScreenX375(47))];
                selectTime.backgroundColor = [UIColor clearColor];
                [selectTime addTarget:self action:@selector(selectedTime) forControlEvents:UIControlEventTouchUpInside];
                [cell addSubview:selectTime];
            }
            UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(ScreenX375(13), ScreenX375(47) - 0.5, SCREEN_WIDTH - ScreenX375(26), 0.5)];
            line.image = [UIImage imageNamed:@"虚线"];
            [cell addSubview:line];
        }
        return cell;
    }else if (indexPath.section == 2) {
        static NSString *cellId = @"textImgCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;

        }
        for (UIView *view in cell.subviews) {
            [view removeFromSuperview];
        }
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(13), ScreenX375(15), ScreenX375(100), ScreenX375(16))];
        titleLabel.text = @"需求描述:";
        titleLabel.textColor = FONTCOLOR_BLACK;
        titleLabel.font = Kfont(14);
        [cell addSubview:titleLabel];
        
        if (!contentText) {
            contentText = [[UITextView alloc] init];
            contentText.frame = CGRectMake(ScreenX375(13), ScreenX375(45), SCREEN_WIDTH - ScreenX375(26), ScreenX375(112));
            contentText.textColor = REXADECIMALCOLOR(@"#c2c2c2");
            contentText.text = @"请写详细需求，已便为您精准匹配专业人才";
            contentText.delegate = self;
            contentText.textAlignment = NSTextAlignmentLeft;
            contentText.font = Kfont(14);
            contentText.layer.borderWidth = 0.5;
            contentText.layer.cornerRadius = ScreenX375(5);
            contentText.clipsToBounds = YES;
            contentText.layer.borderColor = REXADECIMALCOLOR(@"#dcdcdc").CGColor;
        }
        [cell addSubview:contentText];
        
        for (int i = 0; i < _imageArray.count; i++) {
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(ScreenX375(13) + i % 3 * ScreenX375(120), ScreenX375(166) + i / 3 * ScreenX375(120), ScreenX375(110), ScreenX375(110))];
            imageView.image = _imageArray[i];
            [cell addSubview:imageView];
            
            UIButton *deleteBtn = [[UIButton alloc] initWithFrame:CGRectMake(ScreenX375(13) + i % 3 * ScreenX375(120) + ScreenX375(90), ScreenX375(166) + i / 3 * ScreenX375(120), ScreenX375(20), ScreenX375(20))];
            [deleteBtn setImage:ImageWithName(@"删除") forState:UIControlStateNormal];
            deleteBtn.tag = 1000 + i;
            [deleteBtn addTarget:self action:@selector(deleteImg:) forControlEvents:UIControlEventTouchUpInside];
            [cell addSubview:deleteBtn];
        }
        
        if (_imageArray.count < 9) {
            FPCustomButton *addPhotoBtn = [FPCustomButton buttonWithType:UIButtonTypeCustom];
            addPhotoBtn.frame = CGRectMake(ScreenX375(13) + _imageArray.count % 3 * ScreenX375(120), ScreenX375(166) + _imageArray.count / 3 * ScreenX375(120), ScreenX375(110), ScreenX375(110));
            [addPhotoBtn setBackgroundImage:[UIImage imageNamed:@"虚线边框"] forState:UIControlStateNormal];
            [addPhotoBtn setImage:[UIImage imageNamed:@"添加图片"] forState:UIControlStateNormal];
            [addPhotoBtn setTitle:@"添加图片" forState:UIControlStateNormal];
            [addPhotoBtn setTitleColor:RGB_COLOR(210,210,210) forState:UIControlStateNormal];
            addPhotoBtn.titleLabel.font = Kfont(14);
            [addPhotoBtn addTarget:self action:@selector(addPhotoClick) forControlEvents:UIControlEventTouchUpInside];
            [cell addSubview:addPhotoBtn];
        }
        return cell;
    }else if (indexPath.section == 3) {
        static NSString *cellId = @"phoneCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        for (UIView *view in cell.subviews) {
            [view removeFromSuperview];
        }
        UILabel *noteLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(13), 0, ScreenX375(277), ScreenX375(47))];
        NSString *phone = _phoneNum;
        noteLabel.text = [NSString stringWithFormat:@"联系方式：%@****%@",[phone substringToIndex:3],[phone substringFromIndex:7]];
        noteLabel.textColor = REXADECIMALCOLOR(@"#333333");
        noteLabel.font = Kfont(14);
        [cell addSubview:noteLabel];
        
        UIButton *changeBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - ScreenX375(51), 0, ScreenX375(51), ScreenX375(47))];
        [changeBtn setTitle:@"修改" forState:UIControlStateNormal];
        [changeBtn setTitleColor:ThemeColor forState:UIControlStateNormal];
        changeBtn.titleLabel.font = Kfont(12);
        [changeBtn addTarget:self action:@selector(changePhone) forControlEvents:UIControlEventTouchUpInside];
        [cell addSubview:changeBtn];
        
        return cell;
    }else if (indexPath.section == 4) {
        static NSString *cellId = @"phoneCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        for (UIView *subView in cell.subviews) {
            [subView removeFromSuperview];
        }
        bargainBtn = [[UIButton alloc] initWithFrame:CGRectMake((SCREEN_WIDTH - ScreenX375(150)) / 2, 0, ScreenX375(150), ScreenX375(46))];
        [bargainBtn setImage:ImageWithName(@"椭圆1拷贝5") forState:UIControlStateNormal];
        [bargainBtn setImage:ImageWithName(@"选择") forState:UIControlStateSelected];
        [bargainBtn setTitle:@"  能否议价" forState:UIControlStateNormal];
        [bargainBtn setTitleColor:REXADECIMALCOLOR(@"#222222") forState:UIControlStateNormal];
        bargainBtn.titleLabel.font = Kfont(16);
        [bargainBtn addTarget:self action:@selector(isBargain:) forControlEvents:UIControlEventTouchUpInside];
        [cell addSubview:bargainBtn];

        if (_needType == NeedType_Bid) {
            bargainBtn.hidden = NO;
        }else {
            bargainBtn.hidden = YES;
            bargainBtn.selected = NO;
        }
        
        UIButton *commitBtn = [[UIButton alloc] initWithFrame:CGRectMake(ScreenX375(13), ScreenX375(60), SCREEN_WIDTH - ScreenX375(26), ScreenX375(44))];
        [commitBtn setTitle:@"提交" forState:UIControlStateNormal];
        [commitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        commitBtn.titleLabel.font = Kfont(16);
        commitBtn.layer.cornerRadius = ScreenX375(22);
        commitBtn.clipsToBounds = YES;
        commitBtn.backgroundColor = ThemeColor;
        [commitBtn addTarget:self action:@selector(commit) forControlEvents:UIControlEventTouchUpInside];
        [cell addSubview:commitBtn];
        
        return cell;
    }
    UITableViewCell *cell = [[UITableViewCell alloc] init];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        switch (indexPath.row) {
            case 0:
                _needType = NeedType_Bid;
                break;
            case 1:
                _needType = NeedType_Pitch;
                break;
            case 2:
                _needType = NeedType_Piecework;
                break;
            default:
                break;
        }
        [_tableView reloadData];

    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == _needType) {
            return ScreenX375(102);
        }
        return ScreenX375(47);
    }else if (indexPath.section == 1) {
        return ScreenX375(47);
    }else if (indexPath.section == 2) {
        if (_imageArray.count == 9) {
            return ScreenX375(290) + ScreenX375(240);
        }
        return ScreenX375(290) + _imageArray.count / 3 * ScreenX375(120);
    }else if (indexPath.section == 3) {
        return ScreenX375(47);
    }
    return ScreenX375(165);
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return ScreenX375(53);
    }
    return ScreenX375(10);
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ScreenX375(53))];
        view.backgroundColor = [UIColor whiteColor];
        
        UIView *rline = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenX375(15), ScreenX375(3), ScreenX375(23))];
        rline.backgroundColor = ThemeColor;
        [view addSubview:rline];
        
        UILabel *noteLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(13), ScreenX375(15), ScreenX375(200), ScreenX375(24))];
        noteLabel.text = @"您选择的需求是什么";
        noteLabel.textColor = REXADECIMALCOLOR(@"#333333");
        noteLabel.font = Kfont(18);
        [view addSubview:noteLabel];
        
        UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(0, ScreenX375(53) - 0.5, SCREEN_WIDTH, 0.5)];
        line.backgroundColor = LineColor;
        [view addSubview:line];
        
        return view;
    }
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ScreenX375(10))];
    view.backgroundColor = TABLEVIEW_BACKGROUNDCOLOR;
    return view;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self.view endEditing:YES];
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (_needType == NeedType_Pitch) {
        if (textField.tag == 603) {
            _needNum = [textField.text integerValue];
            [self.tableView reloadSections:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(1, 1)] withRowAnimation:UITableViewRowAnimationNone];
        }
    }
}

- (void)addPhotoClick {
    //弹出提示框
    __weak typeof(self)weakSelf = self;
    //初始化提示框
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    //按钮：拍摄
    [alert addAction:[UIAlertAction actionWithTitle:@"拍摄" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf openCamare];
    }]];
    //按钮：从手机相册选择
    [alert addAction:[UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
        [weakSelf openAlbum];
    }]];
    //按钮：取消，类型：UIAlertActionStyleCancel
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - 打开相册
-(void)openAlbum
{
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        
        if (status != PHAuthorizationStatusAuthorized) {
            return ;
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            // init Picker弹出图片选择界面
            CTAssetsPickerController *picker = [[CTAssetsPickerController alloc] init];
            //隐藏空相册
            picker.showsEmptyAlbums = NO;
            //允许显示图片选中后的顺序
            picker.showsSelectionIndex = YES;
            //选择需要弹出的相册，一般我们只需要弹出相机胶卷和自定义相册即可
            picker.assetCollectionSubtypes = @[
                                               @(PHAssetCollectionSubtypeSmartAlbumUserLibrary),
                                               @(PHAssetCollectionSubtypeAlbumRegular)
                                               ];
            // picker delegate
            picker.delegate = self;
            
            // present picker
            [self presentViewController:picker animated:YES completion:nil];
            
        });
    }];
    
}

#pragma mark - 打开相机
-(void)openCamare
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    picker.allowsEditing = YES;
    picker.delegate = self;
    
    [self presentViewController:picker animated:YES completion:nil];
    
}

#pragma mark - UIImagePickerControllerDelegate  图片处理
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    NSLog(@"Picker returned successfully.");
    //    将选择的图片在imageView上显示
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:2];
    [self.imageArray addObject:image];
    
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    //处理完毕，回到个人信息页面
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    
    NSLog(@"Picker was cancelled");
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 设置图片最多选九张
-(BOOL)assetsPickerController:(CTAssetsPickerController *)picker shouldSelectAsset:(PHAsset *)asset
{
    NSInteger max = 9 - self.imageArray.count;
    if (picker.selectedAssets.count < max) return YES;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"注意" message:[NSString stringWithFormat:@"最多选择%ld张图片",(long)max] preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:action];
    //一定要用picker 不能用self 因为当前显示在最上面的控制器是picker 而不是self
    [picker presentViewController:alert animated:YES completion:nil];
    
    return NO;
}

#pragma mark - 选择完毕的时候调用
- (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSArray *)assets
{
    // 关闭图片选择界面
    [picker dismissViewControllerAnimated:YES completion:nil];
    //选择图片时的配置项 (如果不写配置项 会导致请求的图片尺寸出现问题)
    PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
    options.resizeMode = PHImageRequestOptionsResizeModeExact;
    options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
    
    //遍历图片选择的图片显示成九宫格样式
    for (NSInteger i = 0; i < assets.count; i ++) {
        PHAsset *asset = assets[i];
        CGFloat scale = UIScreen.mainScreen.scale;
        CGSize size = CGSizeMake(asset.pixelWidth / scale, asset.pixelHeight / scale);
        
        //请求图片 (需要先用图片管理员请求图片数据 请求完成后 在block里添加图片)
        [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:size contentMode:PHImageContentModeDefault options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
            WeakObj(self);
            
            [selfWeak.imageArray addObject:result];
            if (i == assets.count - 1) {
                NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:2];
                [selfWeak.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
            }
        }];
    }
    
}

- (void)deleteImg:(UIButton *)button {
    [self.imageArray removeObjectAtIndex:button.tag - 1000];
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:2];
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}
    

@end
